#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
模拟前端完整工作流测试
测试：获取预签名URL → 上传COS → 图片处理 → 获取结果
"""

import requests
import uuid
import time
import os
import sys

class FrontendWorkflowTester:
    """前端完整工作流测试器"""
    
    def __init__(self):
        self.gateway_url = "https://www.gongjuxiang.work"
        self.user_id = f"test_user_{uuid.uuid4().hex[:8]}"
        
    def test_complete_workflow(self, image_path: str) -> bool:
        """
        测试完整的前端工作流
        
        流程：
        1. 获取预签名URL（前端步骤1）
        2. 上传图片到COS（前端步骤2）
        3. 请求图片处理（前端步骤3）
        4. 验证结果
        """
        print("=" * 70)
        print("🧪 前端完整工作流测试")
        print("=" * 70)
        print(f"👤 测试用户ID: {self.user_id}")
        print(f"📁 测试图片: {image_path}")
        print()
        
        # 读取测试图片
        if not os.path.exists(image_path):
            print(f"❌ 图片文件不存在: {image_path}")
            return False
        
        with open(image_path, 'rb') as f:
            file_data = f.read()
        
        file_size = len(file_data)
        print(f"📏 图片大小: {file_size / 1024:.2f} KB")
        print()
        
        # ==================== 步骤1: 获取预签名URL ====================
        print("📋 步骤1: 获取COS预签名上传URL...")
        print(f"   API: POST {self.gateway_url}/api/v1/upload/presigned-url")
        
        try:
            step1_start = time.time()
            presigned_response = requests.post(
                f"{self.gateway_url}/api/v1/upload/presigned-url",
                json={
                    'user_id': self.user_id,
                    'file_type': 'image/jpeg',
                    'file_size': file_size,
                    'filename': os.path.basename(image_path)
                },
                timeout=30
            )
            step1_time = time.time() - step1_start
            
            print(f"   状态码: {presigned_response.status_code}")
            print(f"   耗时: {step1_time:.2f}秒")
            
            if presigned_response.status_code != 200:
                print(f"   ❌ 失败: {presigned_response.text}")
                return False
            
            result = presigned_response.json()
            if not result.get('success'):
                print(f"   ❌ 失败: {result.get('error')}")
                return False
            
            presigned_url = result['presigned_url']
            file_key = result['file_key']
            download_url = result['download_url']
            
            print(f"   ✅ 成功获取预签名URL")
            print(f"   文件键: {file_key}")
            print(f"   下载URL: {download_url}")
            print()
            
        except Exception as e:
            print(f"   ❌ 异常: {e}")
            return False
        
        # ==================== 步骤2: 上传到COS ====================
        print("📤 步骤2: 上传图片到COS...")
        print(f"   方法: PUT {presigned_url[:80]}...")
        
        try:
            step2_start = time.time()
            upload_response = requests.put(
                presigned_url,
                data=file_data,
                timeout=60
            )
            step2_time = time.time() - step2_start
            
            print(f"   状态码: {upload_response.status_code}")
            print(f"   耗时: {step2_time:.2f}秒")
            print(f"   上传速度: {file_size / 1024 / step2_time:.2f} KB/s")
            
            if upload_response.status_code not in [200, 204]:
                print(f"   ❌ 上传失败: {upload_response.status_code}")
                print(f"   响应: {upload_response.text}")
                return False
            
            print(f"   ✅ 图片已成功上传到COS")
            print()
            
        except Exception as e:
            print(f"   ❌ 异常: {e}")
            return False
        
        # ==================== 步骤3: 请求图片处理 ====================
        print("🎨 步骤3: 请求图片处理...")
        print(f"   API: POST {self.gateway_url}/api/v1/enhance")
        print(f"   图片URL: {download_url}")
        
        try:
            step3_start = time.time()
            enhance_response = requests.post(
                f"{self.gateway_url}/api/v1/enhance",
                json={
                    'image_url': download_url,
                    'quality_level': 'high'
                },
                timeout=120
            )
            step3_time = time.time() - step3_start
            
            print(f"   状态码: {enhance_response.status_code}")
            print(f"   耗时: {step3_time:.2f}秒")
            
            if enhance_response.status_code != 200:
                print(f"   ❌ 处理失败: {enhance_response.text}")
                return False
            
            enhance_result = enhance_response.json()
            if not enhance_result.get('success'):
                print(f"   ❌ 处理失败: {enhance_result.get('error')}")
                return False
            
            result_url = enhance_result['result_url']
            task_id = enhance_result['task_id']
            processing_time = enhance_result.get('processing_time', 0)
            
            print(f"   ✅ 图片处理成功！")
            print(f"   任务ID: {task_id}")
            print(f"   结果URL: {result_url}")
            print(f"   处理时间: {processing_time:.2f}秒")
            print()
            
        except Exception as e:
            print(f"   ❌ 异常: {e}")
            return False
        
        # ==================== 测试总结 ====================
        total_time = step1_time + step2_time + step3_time
        
        print("=" * 70)
        print("📊 测试结果汇总")
        print("=" * 70)
        print(f"✅ 步骤1 - 获取预签名URL: {step1_time:.2f}秒")
        print(f"✅ 步骤2 - 上传到COS: {step2_time:.2f}秒 ({file_size / 1024:.2f} KB)")
        print(f"✅ 步骤3 - 图片处理: {step3_time:.2f}秒")
        print(f"")
        print(f"⏱️  总耗时: {total_time:.2f}秒")
        print(f"🎉 完整前端工作流测试通过！")
        print("=" * 70)
        
        return True

def main():
    """主函数"""
    tester = FrontendWorkflowTester()
    
    # 获取测试图片路径
    if len(sys.argv) > 1:
        image_path = sys.argv[1]
    else:
        # 默认使用test-data中的图片
        script_dir = os.path.dirname(os.path.abspath(__file__))
        image_path = os.path.join(script_dir, "../test-data/249KB.jpg")
    
    # 执行测试
    success = tester.test_complete_workflow(image_path)
    
    if success:
        print("\n✅ 前端完整工作流测试成功！")
        sys.exit(0)
    else:
        print("\n❌ 测试失败")
        sys.exit(1)

if __name__ == "__main__":
    main()

